<?php

namespace App\Models;

use App\Exceptions\InvalidRequestException;
use Illuminate\Database\Eloquent\Model;

class MatchReport extends Model
{
    //
    const REPORT = 0;
    const EXIT = 1;

    protected $table = 'match_report';

    protected $fillable = ['user_id', 'match_id', 'report_status'];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function match()
    {
        return $this->belongsTo(Match::class, 'match_id', 'id');
    }

    public static function reportMatch($user_id, $match_id)
    {
        $m = Match::find($match_id);
        if (!$m) {
            throw new InvalidRequestException('该比赛不存在', 401);
        }
        $r = self::where('user_id', $user_id)
                ->where('match_id', $match_id)
                ->where('report_status', self::REPORT)->first();
        if ($r) {
            throw new InvalidRequestException('该比赛您已报名', 402);
        }
        $r = new MatchReport();
        $r->name = $m->name;
        $r->user_id = $user_id;
        $r->match_id = $match_id;
        $r->save();
        return true;
    }

    public function scopeSelectNormal($q)
    {
        $q->select('id', 'match_id', 'user_id', 'report_status');
    }
}
